package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Category;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    //清除缓存（
    // ）
    @CacheEvict(value = "setmeal", key = "#setmealDto.categoryId +'::1'")
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        //1.接收信息
        log.info("套餐信息为:{}", setmealDto);
        //2.
        setmealService.saveWithDish(setmealDto);
        //3.
        return R.success("新增套餐成功");
    }

    /**
     * 套餐管理分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        //1.接收信息
        log.info("page:{},pageSize:{},name:{}", page, pageSize, name);
        //2.构建分页
        Page<Setmeal> setmealPage = new Page<>();
        //3.构建条件
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Setmeal::getName, name);
        wrapper.orderByDesc(Setmeal::getUpdateTime);
        //4.分页查询
        setmealService.page(setmealPage, wrapper);
        //5.处理套餐分类
        //5.1定义一个
        Page<SetmealDto> setmealDtoPage = new Page<>();
        //5.2分页基本信息copy(当前页、每页大小、总条数...)，数据不要--records
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");
        //5.3处理数据 （返回一个List<SetmealDto>）
        List<SetmealDto> setmealDtoList = setmealPage.getRecords().stream().map(item -> {//item---Setmeal
            SetmealDto setmealDto = new SetmealDto();//null
            //基本字段copy
            BeanUtils.copyProperties(item, setmealDto);
            //分类name搞定---去分类表查询name
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                setmealDto.setCategoryName(category.getName());
            }
            return setmealDto;//返回一个SetmealDto
        }).collect(Collectors.toList());
        //5.4把这个集合赋值到setmealDtoPage--records属性上
        setmealDtoPage.setRecords(setmealDtoList);
        return R.success(setmealDtoPage);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    //只要删除，就清空缓存
    @CacheEvict(value = "setmeal", allEntries = true)
    public R deleteById(@RequestParam List<Long> ids) {
        //1.接收信息
        log.info("要删除的信息为:{}", ids);
        //2.删除
        setmealService.removeWithDish(ids);
        //3.返回结果
        return R.success("删除成功");
    }

    /**
     * 根据ID查询
     *
     * @param
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> saveById(@PathVariable Long id) {
        //1.获取信息
        log.info("查询的id为:{}", id);
        //2.查询
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        //3.返回结果
        return R.success(setmealDto);
    }

    /**
     * 修改
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        //1.获取信息
        log.info("修改的信息为:{}", setmealDto.toString());
        //2.修改
        setmealService.updateWithDish(setmealDto);
        //3.返回结果
        return R.success("修改成功");
    }

    /**
     * 起售/停售
     *
     * @param status
     * @param ids
     * @return
     */

    @PostMapping("/status/{status}")
    public R<String> upstatus(@PathVariable("status") Integer status, @RequestParam List<Long> ids) {
        //1.接收信息
        log.info("修改的status，ids为:{}", status, ids);
        //2.修改状态
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ids != null, Setmeal::getId, ids);
        //根据数据进行批量查询
        List<Setmeal> list = setmealService.list(wrapper);
        for (Setmeal setmeal : list) {
            if (setmeal != null) {
                setmeal.setStatus(status);
                setmealService.updateById(setmeal);
            }
        }
        return R.success("售卖状态修改成功");
    }

    /**
     * 根据套餐分类查询套餐信息
     *
     * @param setmeal
     * @return
     */
    //K=setmeal::xxx::1
    //unless:返回值中data属性==null不添加，不等于null就添加
    @Cacheable(value = "setmeal", key = "#setmeal.categoryId +'::'+ #setmeal.status", unless = "#result.data == null ")
    @GetMapping("/list")
    public R list(Setmeal setmeal) {
        //1.接收信息
        log.info("根据套餐分类查询套餐信息:{}", setmeal);
        //2.构造查询条件
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        wrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        //3.套餐查询
        List<Setmeal> list = setmealService.list(wrapper);
        return R.success(list);
    }

    /**
     * 根据套餐id查询菜品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R dish(@PathVariable Long id) {
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(wrapper);
        return R.success(list);
    }
}
